import 'dart:async';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/net/login_connect.dart';
import 'package:kkhousekeep/page/home/home_main_page.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';
import 'package:kkhousekeep/tools/string_ext.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

import '../../config/constant.dart';
import '../../models/login_owner_entity.dart';
import '../../models/login_property_entity.dart';
import '../../net/respnse_code.dart';
import '../authorization/authorization_page.dart';
import 'forget_pwd.dart';

class LoginController extends GetxController {
  TextEditingController accountController = TextEditingController();
  TextEditingController pwdController = TextEditingController();

  ///页面显示状态
  var isOwner = true.obs;

  ///是否通过手机号码登录
  var isLoginByPhone = true.obs;

  ///是否置灰按钮
  var isButtonAsh = true.obs;

  ///是否隐藏密码
  var isHidePwd = true.obs;

  ///防止用户在倒计时期间修改文本，可再次发送短信
  var hadSendCode = false.obs;

  ///能否发送验证码
  var canSendCode = false.obs;

  ///倒计时文本
  var countDown = 60.obs;

  ///是否勾选协议
  var isSelectedAgreement = false.obs;

  late Timer _timer;
  late List<String> splitList;
  late LoginConnect loginConnect;

  @override
  void onInit() {
    super.onInit();
    _timer = Timer(const Duration(minutes: 0), () {});
    loginConnect = Get.put(LoginConnect());
    loadPhone();
  }

  Future<void> loadPhone() async {
    var oldPhone = await getSp().getPhone();
    if (oldPhone != "") {
      accountController.text = oldPhone;
      canSendCode.value = true;
    }
  }

  @override
  void onClose() {
    _timer.cancel();
    accountController.dispose();
    pwdController.dispose();
    super.onClose();
  }

  ///修改密码显示状态
  void changePwdState() {
    isHidePwd.value = !isHidePwd.value;
  }

  ///修改用户状态
  void changeUserState() {
    pwdController.text = "";
    isLoginByPhone.value = true;
    isButtonAsh.value = true;
    isOwner.value = !isOwner.value;
  }

  ///获取验证码
  void getCode() async {
    if (!canSendCode.isTrue) {
      return;
    }
    if (!accountController.text.checkCNPhone()) {
      ToastUtils.showToast(tip: "请输入正确的手机号码");
      return;
    }
    var response = await loginConnect.sendCode(accountController.text,
        isOwner: isOwner.value);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      _startCountDown();
      return;
    }
    if (response.code == ResponseCode.errorCode) {
      ToastUtils.showToast(tip: "您的号码没有权限");
      return;
    }
    DialogUtil.showNetworkFail();
  }

  ///修改页面状态
  void changeLoginMethod() {
    accountController.text = "";
    pwdController.text = "";
    isButtonAsh.value = true;
    isHidePwd.value = true;
    isLoginByPhone.value = !isLoginByPhone.value;
  }

  ///倒计时
  void _startCountDown() {
    hadSendCode.value = true;
    canSendCode.value = false;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countDown--;
      if (countDown.value == 0) {
        timer.cancel();
        hadSendCode.value = false;
        canSendCode.value = true;
        countDown.value = 60;
      }
    });
  }

  ///观察账号文本
  void observerAccountText(String text) {
    canSendCode.value = false;
    if (text.isNotEmpty && !hadSendCode.value) {
      canSendCode.value = true;
    }
    if (text.isNotEmpty && pwdController.text.isNotEmpty) {
      isButtonAsh.value = false;
      return;
    }
    isButtonAsh.value = true;
  }

  ///观察密码文本
  observerPwdText(String text) {
    if (accountController.text.isNotEmpty && pwdController.text.isNotEmpty) {
      isButtonAsh.value = false;
      return;
    }
    isButtonAsh.value = true;
  }

  ///构建忘记密码页
  void buildForgetPage() {
    hadSendCode.value = false;
    if (_timer.isActive) {
      _timer.cancel();
    }
    Get.to(() => const BuildForgetPwdPage());
  }

  ///修改协议勾选状态
  void changeAgreementState() {
    isSelectedAgreement.value = !isSelectedAgreement.value;
  }

  ///登录处理方法
  void login() {
    if (isLoginByPhone.value) {
      loginByPhone();
      return;
    }
    loginByPwd();
    return;
  }

  ///以手机号登录
  Future<void> loginByPhone() async {
    //业主端登录处理
    if (isOwner.value) {
      if (!isSelectedAgreement.value) {
        ToastUtils.showToast(tip: "请确认已阅读用户服务协议");
        return;
      }
      if (!accountController.text.checkCNPhone()) {
        ToastUtils.showToast(tip: "请输入正确的手机号码");
        return;
      }
      var response = await loginConnect.loginWithOwner(
          accountController.text, pwdController.text);
      _handleResponseWithOwner(response);
      return;
    }

    //物业端处理
    if (!accountController.text.checkCNPhone()) {
      ToastUtils.showToast(tip: "请输入正确的手机号码");
      return;
    }
    var response = await loginConnect.loginByPhone(
        accountController.text, pwdController.text);
    _handleResponseWithProperty(response);
  }

  ///已账号密码形式登录，只有物业端可用
  Future<void> loginByPwd() async {
    String pwd = md5
        .convert(utf8.encode("${pwdController.text}${Constant.pwdKey}"))
        .toString()
        .substring(0, 32);
    var response = await loginConnect.loginByPwd(accountController.text, pwd);
    _handleResponseWithProperty(response);
  }

  ///处理物业响应
  void _handleResponseWithProperty(LoginPropertyEntity? response) {
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      ToastUtils.showToast(tip: "登录成功");
      getSp().setUserType(UserType.property);
      getSp().setUserName(response.obj.username);
      getSp().setAccessToken(response.obj.accessToken);
      getSp().setUserHeadPortrait(response.obj.headPortrait);
      getSp().setCid(response.obj.cid);
      getSp().setCname(response.obj.cname);
      getSp().setUid(response.obj.uid);
      getSp().setRelation(response.obj.relation);
      if (isLoginByPhone.value) {
        getSp().setPhone(accountController.text);
      }
      //调整至物业端的首页
      Get.offAll(() => const HomeMainPage(
            userType: UserType.property,
          ));
      return;
    }
    if (response.code == ResponseCode.errorCode) {
      var tip = isLoginByPhone.value ? "验证码错误" : "账号信息有误";
      ToastUtils.showToast(tip: tip);
      return;
    }
    DialogUtil.showNetworkFail();
  }

  ///处理业主响应
  void _handleResponseWithOwner(LoginOwnerEntity? response) {
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.errorCode) {
      ToastUtils.showToast(tip: "验证码错误");
      return;
    }
    if (response.code == ResponseCode.success) {
      var obj = response.obj;
      //业主未通过认证
      if (!response.obj.roomCheckPass) {
        getSp().setRoomCheckPass(false);
        getSp().setUserType(UserType.tenant);
        getSp().setAccessToken(obj.token);
        getSp().setOwnerName(obj.ownerName);
        getSp().setPhone(accountController.text);
        Get.offAll(
          () => const BuildAuthorizationPage(
            isJumpToMePage: true,
          ),
        );
        return;
      }
      //通过认证
      UserType userType = getUserType(obj.ownerType);
      getSp().setRoomCheckPass(true);
      getSp().setUserType(userType);
      getSp().setAccessToken(obj.token);
      getSp().setOwnerName(obj.ownerName);
      getSp().setPhone(accountController.text);
      getSp().setUserHeadPortrait(obj.ownerImage);
      Get.offAll(() => HomeMainPage(userType: userType));
      return;
    }
    DialogUtil.showNetworkFail();
  }

  UserType getUserType(String ownerType) {
    return UserType.values.firstWhere((element) => element.value == ownerType,
        orElse: () => UserType.tenant);
  }
}

///用户类型
enum UserType {
  //业主
  owner(value: "1001"),
  //家庭成员
  family(value: "1002"),
  //租户
  tenant(value: "1003"),
  //其它
  other(value: "4000"),
  //物业
  property(value: "1005");

  final String value;

  const UserType({
    required this.value,
  });
}
